﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Slam.SharePoint;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.SharePoint.Client.Services;
using Microsoft.SharePoint.WebControls;

namespace Slam
{
	[ServiceContract(Namespace = "")]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
	[BasicHttpBindingServiceMetadataExchangeEndpoint]
	[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
	public class SlamService
	{
		[WebInvoke(Method = "GET",
		ResponseFormat = WebMessageFormat.Json,
		UriTemplate = "GetNewSlamId?list={listName}",
		BodyStyle = WebMessageBodyStyle.Bare)]
		[OperationContract]
		public string GetNewSlamId(string listName)
		{
			string slamId = "";
			SPWeb site = SPControl.GetContextWeb(HttpContext.Current);
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite siteCollection = new SPSite(site.Site.ID))
				{
					using (SPWeb web = siteCollection.AllWebs[site.ID])
					{
						SPList list = web.Lists[listName];
						SPListItem listItem = list.Items.Add();
						slamId = Convert.ToString(listItem.GetUniqueId(true, false));
					}
				}
			});
			return slamId;
		}

		[WebInvoke(Method = "GET",
		ResponseFormat = WebMessageFormat.Json,
		UriTemplate = "GetNewSlamIdByContentType?list={listName}&contentType={contentTypeName}",
		BodyStyle = WebMessageBodyStyle.Bare)]
		[OperationContract]
		public string GetNewSlamIdByContentType(string listName, string contentTypeName)
		{
			string slamId = "";
			SPWeb site = SPControl.GetContextWeb(HttpContext.Current);
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite siteCollection = new SPSite(site.Site.ID))
				{
					using (SPWeb web = siteCollection.AllWebs[site.ID])
					{
						SPList list = site.Lists[listName];
						SPContentType contentType = null;
						if (!String.IsNullOrEmpty(contentTypeName))
						{
							try
							{
								contentType = list.ContentTypes[contentTypeName];
							}
							catch { }
						}

						SPListItem listItem = list.Items.Add();
						if (contentType != null)
							listItem["ContentTypeId"] = contentType.Id;

						slamId = Convert.ToString(listItem.GetUniqueId(true, false));
					}
				}
			});
			return slamId;
		}
	}
}
